#include <iostream>
#include <memory>
#include <cstdlib>
#include <signal.h>
#include "Daemon.hpp"
#include "Server.hpp"

// static void TestServer(int sockfd)
// {
//     std::cout<<"run... sockfd:"<<sockfd<<std::endl;
//     sleep(1);
// }

static ns_protocol::Response calculate(const ns_protocol::Request &request)
{
    ns_protocol::Response resp;
    switch (request._op)
    {
    case '+':
        resp._result = request._x + request._y;
        resp._code = 0;
        break;
    case '-':
        resp._result = request._x - request._y;
        resp._code = 0;
        break;
    case '*':
        resp._result = request._x * request._y;
        resp._code = 0;
        break;
    case '/':
        if (request._y == 0)
            return ns_protocol::Response(-1, 1);
        resp._result = request._x / request._y;
        resp._code = 0;
        break;
    case '%':
        if (request._y == 0)
            return ns_protocol::Response(-1, 2);
        resp._result = request._x % request._y;
        resp._code = 0;
        break;
    default:
        return ns_protocol::Response(-1, 3);
        break;
    }
    return resp;
}

static void NetCal(int sockfd)
{  
    std::string message;
    while (true)
    {
        // 1.读取数据
        if(!ns_protocol::Recv(sockfd,&message))
        {
            break;
        }
        // 2.协议解析
        std::string str=ns_protocol::DeCode(message);
        if(str.empty()) 
        {   
            continue; // 如果没有一个完整的数据,则继续读取
        }

        // std::cout<<"DeCode success"<<std::endl;

        // 3.反序列化
        ns_protocol::Request request;
        request.Deserialization(str);
        // 4.业务逻辑+序列化
        ns_protocol::Response responce(calculate(request));
        // 5.协议制作
        std::string ret=ns_protocol::EnCode(responce.Serialization());
        // std::cout<<"EnCode success"<<std::endl;
        // 6.写回数据
        ns_protocol::Send(sockfd, ret);
        // ns_protocol::Send(sockfd, responce.Serialization());
    }
}

int main(int argc, char *argv[], char *env[])
{
    if (argc != 2)
    {
        std::cout << argv[0] << " port" << std::endl;
        exit(1);
    }

    Daemon();

    std::unique_ptr<ns_server::TcpServer> server(new ns_server::TcpServer(atoi(argv[1])));

    signal(SIGPIPE,SIG_IGN); // 写端关闭时,该读端收到SIGPIPE信号则进行忽略

    server->AddService(NetCal);
    server->Start();

    return 0;
}